// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <vector>
#include <pollux/dwio/common/encryption/encryption.h>
#include <pollux/common/exception/exception.h>
#include <pollux/dwio/dwrf/common/wrap/dwrf-proto-wrapper.h>

namespace kumo::pollux::dwrf::encryption {

proto::Encryption_KeyProvider toProto(
    dwio::common::encryption::EncryptionProvider provider);

dwio::common::encryption::EncryptionProvider fromProto(
    proto::Encryption_KeyProvider provider);

class FieldEncryptionSpecification {
 public:
  // TODO: support fields other than top level ones
  FieldEncryptionSpecification& withIndex(uint32_t index) {
    index_ = index;
    return *this;
  }

  FieldEncryptionSpecification& withEncryptionProperties(
      const std::shared_ptr<
          const dwio::common::encryption::EncryptionProperties>& props) {
    DWIO_ENSURE(props.get(), "props is required");
    props_ = props;
    return *this;
  }

 private:
  std::optional<uint32_t> index_;
  std::shared_ptr<const dwio::common::encryption::EncryptionProperties> props_;

  friend class EncryptionHandler;
};

class EncryptionSpecification {
 public:
  explicit EncryptionSpecification(
      dwio::common::encryption::EncryptionProvider provider)
      : providerType_{provider} {}

  EncryptionSpecification& withRootEncryptionProperties(
      const std::shared_ptr<
          const dwio::common::encryption::EncryptionProperties>& props);

  EncryptionSpecification& withEncryptedField(
      const FieldEncryptionSpecification& spec);

  dwio::common::encryption::EncryptionProvider providerType() const {
    return providerType_;
  }

  const std::shared_ptr<const dwio::common::encryption::EncryptionProperties>&
  rootProps() const {
    return rootProps_;
  }

  const std::vector<FieldEncryptionSpecification>& fieldSpecs() const {
    return fieldSpecs_;
  }

 private:
  dwio::common::encryption::EncryptionProvider providerType_;
  std::shared_ptr<const dwio::common::encryption::EncryptionProperties>
      rootProps_;
  std::vector<FieldEncryptionSpecification> fieldSpecs_;
};

} // namespace kumo::pollux::dwrf::encryption
